<template>
  <view v-if="visible" class="modal-mask" @tap="handleMaskClick">
    <view class="modal-container" @tap.stop>
      <view class="modal-header">
        <text class="modal-title">更新记录</text>
        <view class="modal-close" @tap="handleClose">
          <text class="close-text">×</text>
        </view>
      </view>
      
      <view class="modal-body">
        <view class="form-item" :class="{ 'modified': isCurrentValueModified }">
          <text class="form-label">当前值</text>
          <view class="form-input disabled">{{ getCurrentValue() }}</view>
        </view>
        
        <view class="form-item" :class="{ 'modified': isUpdatedValueModified }">
          <text class="form-label">更新值</text>
          <input 
            class="form-input" 
            type="text" 
            v-model="updatedValue" 
            placeholder="请输入更新值"
          />
        </view>
        
        <view class="form-item" :class="{ 'modified': isProblemModified }">
          <text class="form-label">问题描述</text>
          <textarea 
            class="form-input textarea-input" 
            v-model="accProblem" 
            placeholder="请输入问题描述"
            maxlength="200"
          ></textarea>
        </view>
        
        <view class="form-item" :class="{ 'modified': areImagesModified }">
          <text class="form-label">佐证照片</text>
          <view class="upload-area">
            <!-- 已上传的图片预览 -->
            <view class="image-list">
              <view 
                class="upload-preview" 
                v-for="(image, index) in imageList" 
                :key="index"
              >
                <!-- 加载状态指示器 -->
                <view 
                  v-if="imageLoadingStates[index]" 
                  class="loading-indicator"
                >
                  <text class="loading-text">加载中...</text>
                </view>
                
                <image 
                  class="preview-image" 
                  :src="getImageUrl(image)" 
                  mode="aspectFill"
                  @tap="previewImage(index)"
                  @error="handleImageError(index)"
                  @load="handleImageLoad(index)"
                  :style="{ opacity: imageLoadingStates[index] ? 0.5 : 1 }"
                ></image>
                
                <!-- 图片信息提示 -->
                <view 
                  v-if="image.isNewUpload" 
                  class="upload-badge"
                >
                  新
                </view>
                
                <view class="delete-image" @tap="removeImage(index)">×</view>
                <view class="view-image" @tap="previewImage(index)">👁</view>
              </view>
              
              <!-- 上传按钮 -->
              <view class="upload-button" @tap="chooseImage" v-if="imageList.length < maxImages">
                <text class="upload-icon">+</text>
                <text class="upload-text">上传照片</text>
              </view>
            </view>
            
            <view class="upload-tip" v-if="imageList.length > 0">
              <text>已上传 {{ imageList.length }}/{{ maxImages }} 张照片</text>
            </view>
          </view>
        </view>
        
        <view class="form-actions">
          <button class="btn btn-cancel" @tap="handleClose">取消</button>
          <button class="btn btn-submit" @tap="handleSubmit">提交修改</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, computed } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  recordData: {
    type: Object,
    default: () => ({
      id: null,
      currentValue: '',
      type: ''
    })
  }
});

const emit = defineEmits(['close', 'submit']);

const updatedValue = ref('');
const imageList = ref([]);
const accProblem = ref('');
const maxImages = 5; // 最多支持5张照片
const imageLoadingStates = ref({}); // 图片加载状态管理

// 全局存储管理 - 确保跨组件实例持久化
if (typeof window !== 'undefined' && !window.recordUpdateStorage) {
  window.recordUpdateStorage = {};
}

// 计算是否有修改
const isCurrentValueModified = computed(() => false); // 当前值不可修改
const isUpdatedValueModified = computed(() => {
  return updatedValue.value !== '' && updatedValue.value.trim() !== '';
});
const areImagesModified = computed(() => {
  return imageList.value.length > 0;
});
const isProblemModified = computed(() => {
  return accProblem.value !== '' && accProblem.value.trim() !== '';
});

// 获取当前值的方法
function getCurrentValue() {
  if (!props.recordData) {
    return '';
  }
  
  // 优先从 recordData 中获取 currentValue
  if (props.recordData.currentValue !== undefined && props.recordData.currentValue !== null) {
    return props.recordData.currentValue;
  }
  
  // 如果没有 currentValue，尝试从 count 字段获取
  if (props.recordData.count !== undefined && props.recordData.count !== null) {
    return props.recordData.count;
  }
  
  // 如果都没有，返回空字符串
  return '';
}

// 加载暂存数据的通用函数
function loadExistingData() {
  if (!props.recordData) return;
  
  console.log('=== 加载暂存数据到表单 ===');
  console.log('recordData:', props.recordData);
  console.log('全局存储:', window.recordUpdateStorage);

  const recordKey = `${props.recordData.misCode}_${props.recordData.siteTaskId}_${props.recordData.rowId}_${props.recordData.type}`
  console.log('计算出的recordKey:', recordKey);
  const comfirmData = window.recordUpdateStorage[recordKey];
  if (comfirmData) {
    console.log('从全局存储加载数据:', comfirmData);
    
    updatedValue.value = comfirmData.updatedValue || '';
    accProblem.value = comfirmData.accProblem || '';
    
    // 处理图片数据，支持多种格式
    const imageData = comfirmData.imageList || comfirmData.photo_path || [];
    imageList.value = processImageData(imageData);
    
    console.log('加载的图片数据:', imageList.value);
  }
}

// 处理图片数据，统一格式
function processImageData(imageData) {
  // 处理各种空值情况
  if (!imageData) {
    console.log('图片数据为null或undefined');
    return [];
  }
  
  if (!Array.isArray(imageData)) {
    console.log('图片数据不是数组格式:', typeof imageData, imageData);
    return [];
  }
  
  if (imageData.length === 0) {
    console.log('图片数组为空');
    return [];
  }
  
  console.log('开始处理图片数据，总数:', imageData.length);
  
  return imageData.map((item, index) => {
    console.log(`处理第${index + 1}张图片:`, item);
    
    // 检查空值
    if (!item) {
      console.warn(`第${index + 1}张图片数据为空`);
      return null;
    }
    
    // 如果已经是标准格式 {url: string, file: object}
    if (item && typeof item === 'object' && item.url) {
      // 验证URL是否有效
      const url = item.url;
      if (typeof url === 'string' && url.trim().length > 0) {
        return {
          url: url.trim(),
          file: item.file || null,
          originalPath: item.originalPath || url.trim(),
          isNewUpload: item.isNewUpload || false,
          id: item.id || `img_${Date.now()}_${index}`,
          timestamp: item.timestamp || Date.now(),
          size: item.size || 0,
          type: item.type || 'image/jpeg'
        };
      } else {
        console.warn(`第${index + 1}张图片URL无效:`, url);
        return null;
      }
    }
    
    // 如果是字符串格式的图片数据
    if (typeof item === 'string') {
      const trimmedItem = item.trim();
      if (trimmedItem.length === 0) {
        console.warn(`第${index + 1}张图片字符串为空`);
        return null;
      }
      return {
        url: trimmedItem,
        file: null,
        originalPath: trimmedItem,
        isNewUpload: false,
        timestamp: Date.now()
      };
    }
    
    // 如果是后端返回的格式 {id: string, data: string}
    if (item && typeof item === 'object' && (item.id || item.data)) {
      const imageUrl = item.data || item.url || item;
      if (typeof imageUrl === 'string' && imageUrl.trim().length > 0) {
        return {
          url: imageUrl.trim(),
          file: null,
          originalPath: imageUrl.trim(),
          isNewUpload: false,
          id: item.id || null,
          timestamp: Date.now()
        };
      } else {
        console.warn(`第${index + 1}张图片数据无效:`, imageUrl);
        return null;
      }
    }
    
    console.warn(`第${index + 1}张图片格式未知:`, typeof item, item);
    return null;
  }).filter(Boolean); // 过滤掉null值
}

// 监听模态框显示状态，加载暂存数据
watch(() => props.visible, (newVal) => {
  if (newVal && props.recordData) {
    console.log('=== 模态框打开，开始加载数据 ===');
    console.log('当前recordData:', props.recordData);
    
    // 重置表单数据
    updatedValue.value = '';
    accProblem.value = '';
    imageList.value = [];
    
    // 优先从全局存储加载最新的暂存数据
    const recordKey = `${props.recordData.misCode}_${props.recordData.siteTaskId}_${props.recordData.rowId}_${props.recordData.type}`;
    console.log('构建的recordKey:', recordKey);
    
    let hasLoadedFromStorage = false;
    
    if (typeof window !== 'undefined' && window.recordUpdateStorage && window.recordUpdateStorage[recordKey]) {
      const storedRecord = window.recordUpdateStorage[recordKey];
      console.log('从全局存储加载最新数据:', storedRecord);
      
      // 加载存储的数据
      updatedValue.value = storedRecord.updatedValue || storedRecord.right_value || '';
      accProblem.value = storedRecord.accProblem || storedRecord.acc_problem || '';
      
      // 处理图片数据 - 优先使用存储的imageList
      const imageData = storedRecord.imageList || storedRecord.photo_path || [];
      if (Array.isArray(imageData) && imageData.length > 0) {
        console.log('从存储加载图片数据，数量:', imageData.length);
        imageList.value = processImageData(imageData);
        hasLoadedFromStorage = true;
      }
    }
    
    // 如果全局存储中没有数据，则从recordData加载
    if (!hasLoadedFromStorage) {
      console.log('全局存储中无数据，从recordData加载');
      
      // 加载预填充数据
      if (props.recordData.updatedValue || props.recordData.right_value) {
        updatedValue.value = props.recordData.updatedValue || props.recordData.right_value || '';
      }
      
      if (props.recordData.accProblem || props.recordData.acc_problem) {
        accProblem.value = props.recordData.accProblem || props.recordData.acc_problem || '';
      }
      
      // 处理图片数据
      if (props.recordData.imageList && Array.isArray(props.recordData.imageList)) {
        console.log('从recordData.imageList加载图片数据:', props.recordData.imageList);
        imageList.value = processImageData(props.recordData.imageList);
      } else if (props.recordData.photo_path && Array.isArray(props.recordData.photo_path)) {
        console.log('从recordData.photo_path加载图片数据:', props.recordData.photo_path);
        imageList.value = processImageData(props.recordData.photo_path);
      }
    }
    
    console.log('=== 数据加载完成 ===');
    console.log('最终加载的数据:', {
      updatedValue: updatedValue.value,
      accProblem: accProblem.value,
      imageCount: imageList.value.length
    });
  }
});

// 监听recordData变化，重新加载数据
watch(() => props.recordData, (newData) => {
  if (newData && props.visible) {
    console.log('recordData变化，重新加载数据:', newData);
    
    // 如果recordData中直接包含图片数据，优先使用
    if (newData.imageList && Array.isArray(newData.imageList)) {
      console.log('从recordData直接加载图片数据:', newData.imageList);
      imageList.value = processImageData(newData.imageList);
    } else if (newData.photo_path && Array.isArray(newData.photo_path)) {
      console.log('从recordData的photo_path加载图片数据:', newData.photo_path);
      imageList.value = processImageData(newData.photo_path);
    }
    
    // 加载其他数据
    if (newData.updatedValue || newData.right_value) {
      updatedValue.value = newData.updatedValue || newData.right_value || '';
    }
    
    if (newData.accProblem || newData.acc_problem) {
      accProblem.value = newData.accProblem || newData.acc_problem || '';
    }
    
    // 然后再调用通用加载函数（可能会从全局存储覆盖）
    loadExistingData();
  }
}, { deep: true });

// 实时保存数据变化
watch([updatedValue, imageList, accProblem], () => {
  if (props.recordData && props.visible) {
    // 使用与加载时完全一致的键构建逻辑
    const recordKey = `${props.recordData.misCode}_${props.recordData.siteTaskId}_${props.recordData.rowId}_${props.recordData.type}`;
    
    const recordData = {
      updatedValue: updatedValue.value,
      imageList: [...imageList.value], // 深拷贝图片列表
      accProblem: accProblem.value,
      timestamp: Date.now(),
      // 保持后端字段名兼容性
      right_value: updatedValue.value,
      acc_problem: accProblem.value,
      photo_path: [...imageList.value], // 同时保存为photo_path格式
      // 保存项目和站点信息
      projectId: props.recordData.misCode,
      siteId: props.recordData.siteTaskId
    };
    
    // 保存到全局存储
    if (typeof window !== 'undefined') {
      if (!window.recordUpdateStorage) {
        window.recordUpdateStorage = {};
      }
      window.recordUpdateStorage[recordKey] = recordData;
      console.log('实时保存到全局存储:', recordKey);
      console.log('保存的数据:', {
        updatedValue: recordData.updatedValue,
        imageCount: recordData.imageList.length,
        accProblem: recordData.accProblem
      });
    }
  }
}, { deep: true });

function handleMaskClick(e) {
  if (e.target === e.currentTarget) {
    handleClose();
  }
}

function handleClose() {
  // 在关闭前检查是否有内容修改
  const hasUpdatedValue = updatedValue.value && updatedValue.value.trim() !== '';
  const hasImages = imageList.value.length > 0;
  const hasProblem = accProblem.value && accProblem.value.trim() !== '';
  
  // 如果有任何修改内容，触发高亮
  const hasAnyModification = hasUpdatedValue || hasImages || hasProblem;
  
  console.log('模态框关闭检查:', {
    hasUpdatedValue,
    hasImages,
    hasProblem,
    hasAnyModification
  });
  
  // 清理表单数据
  updatedValue.value = '';
  accProblem.value = '';
  imageList.value = [];
  
  // 清理图片加载状态
  imageLoadingStates.value = {};
  
  console.log('模态框关闭，数据已清理');
  
  // 发送关闭事件，并传递是否有修改的信息
  emit('close', { hasModification: hasAnyModification });
}

function chooseImage() {
  const remainingCount = maxImages - imageList.value.length;
  
  if (remainingCount <= 0) {
    uni.showToast({ 
      title: `最多只能上传${maxImages}张照片`, 
      icon: 'none' 
    });
    return;
  }
  
  console.log('开始选择图片，剩余可选数量:', remainingCount);
  
  uni.chooseImage({
    count: remainingCount,
    sizeType: ['compressed'], // 使用压缩图片
    sourceType: ['album', 'camera'],
    success: (res) => {
      console.log('图片选择成功:', res);
      console.log('选择的图片路径:', res.tempFilePaths);
      console.log('图片文件信息:', res.tempFiles);
      
      // 验证返回的数据
      if (!res.tempFilePaths || res.tempFilePaths.length === 0) {
        console.error('未获取到图片路径');
        uni.showToast({ title: '未获取到图片', icon: 'none' });
        return;
      }
      
      // 处理新选择的图片 - 优化处理逻辑
      const newImages = [];
      
      res.tempFilePaths.forEach((path, index) => {
        // 验证路径有效性
        if (!path || typeof path !== 'string' || path.trim().length === 0) {
          console.warn(`第${index + 1}张图片路径无效:`, path);
          return;
        }
        
        const trimmedPath = path.trim();
        console.log(`处理第${index + 1}张图片路径:`, trimmedPath);
        
        // 创建图片数据对象
        const imageData = {
          url: trimmedPath,
          originalPath: trimmedPath, // 保存原始路径用于调试
          file: res.tempFiles && res.tempFiles[index] ? res.tempFiles[index] : {
            path: trimmedPath,
            size: res.tempFiles && res.tempFiles[index] ? res.tempFiles[index].size : 0,
            name: `image_${Date.now()}_${index}.jpg`,
            type: 'image/jpeg'
          },
          timestamp: Date.now(),
          isNewUpload: true // 标记为新上传的图片
        };
        
        console.log(`第${index + 1}张图片数据:`, imageData);
        newImages.push(imageData);
      });
      
      if (newImages.length === 0) {
        console.error('没有有效的图片数据');
        uni.showToast({ title: '图片处理失败', icon: 'none' });
        return;
      }
      
      // 添加到图片列表
      const oldCount = imageList.value.length;
      imageList.value = [...imageList.value, ...newImages];
      const newCount = imageList.value.length;
      
      // 初始化新图片的加载状态
      newImages.forEach((_, index) => {
        const imageIndex = oldCount + index;
        imageLoadingStates.value[imageIndex] = true;
        console.log(`初始化第${imageIndex + 1}张图片加载状态`);
      });
      
      console.log(`图片添加完成: ${oldCount} -> ${newCount}`);
      console.log('当前图片列表:', imageList.value);
      console.log('当前加载状态:', imageLoadingStates.value);
      
      // 显示成功提示
      uni.showToast({ 
        title: `已添加${newImages.length}张照片`, 
        icon: 'success',
        duration: 1500
      });
      
      // 如果达到最大数量，提示用户
      if (imageList.value.length >= maxImages) {
        setTimeout(() => {
          uni.showToast({ 
            title: `已达到最大上传数量${maxImages}张`, 
            icon: 'none',
            duration: 2000
          });
        }, 1600);
      }
    },
    fail: (err) => {
      console.error('选择图片失败:', err);
      
      // 根据错误类型显示不同提示
      let errorMsg = '选择图片失败';
      if (err.errMsg) {
        if (err.errMsg.includes('cancel')) {
          console.log('用户取消选择图片');
          return; // 用户取消，不显示错误提示
        } else if (err.errMsg.includes('permission')) {
          errorMsg = '没有相机或相册权限';
        } else if (err.errMsg.includes('fail')) {
          errorMsg = '图片选择失败，请重试';
        }
      }
      
      uni.showToast({ 
        title: errorMsg, 
        icon: 'none',
        duration: 2000
      });
    }
  });
}

function removeImage(index) {
  console.log('删除图片，索引:', index);
  const image = imageList.value[index];
  if (image) {
    console.log('删除的图片数据:', image);
  }
  
  // 清理加载状态
  delete imageLoadingStates.value[index];
  
  // 删除图片
  imageList.value.splice(index, 1);
  
  // 重新整理加载状态索引
  const newLoadingStates = {};
  Object.keys(imageLoadingStates.value).forEach(key => {
    const oldIndex = parseInt(key);
    if (oldIndex > index) {
      newLoadingStates[oldIndex - 1] = imageLoadingStates.value[key];
    } else if (oldIndex < index) {
      newLoadingStates[oldIndex] = imageLoadingStates.value[key];
    }
  });
  imageLoadingStates.value = newLoadingStates;
  
  console.log('图片删除完成，当前列表长度:', imageList.value.length);
}

// 处理图片加载完成
function handleImageLoad(index) {
  console.log(`第${index + 1}张图片加载完成`);
  delete imageLoadingStates.value[index];
  
  const image = imageList.value[index];
  if (image) {
    console.log('加载完成的图片:', getImageUrl(image));
  }
}

// 获取图片URL，优化处理逻辑
function getImageUrl(image) {
  if (!image) {
    console.warn('图片数据为空');
    return '';
  }
  
  console.log('处理图片URL:', image);
  
  // 如果是对象格式
  if (typeof image === 'object' && image !== null) {
    // 优先使用url字段
    if (image.url) {
      return processImageUrl(image.url);
    }
    
    // 其次使用data字段（后端返回格式）
    if (image.data) {
      return processImageUrl(image.data);
    }
    
    // 最后尝试src字段
    if (image.src) {
      return processImageUrl(image.src);
    }
    
    console.warn('对象中没有找到有效的图片URL字段:', image);
    return '';
  }
  
  // 如果是字符串格式
  if (typeof image === 'string') {
    return processImageUrl(image);
  }
  
  console.warn('无法识别的图片格式:', typeof image, image);
  return '';
}

// 处理图片URL的核心函数
function processImageUrl(url) {
  if (!url || typeof url !== 'string') {
    console.warn('URL不是有效字符串:', url);
    return '';
  }
  
  const trimmedUrl = url.trim();
  
  if (trimmedUrl.length === 0) {
    console.warn('URL为空字符串');
    return '';
  }
  
  console.log('处理URL:', trimmedUrl);
  
  // 1. 已经是完整的data URL - 直接返回
  if (trimmedUrl.startsWith('data:image/')) {
    console.log('检测到完整data URL');
    return trimmedUrl;
  }
  
  // 2. HTTP/HTTPS URL - 直接返回
  if (trimmedUrl.startsWith('http://') || trimmedUrl.startsWith('https://')) {
    console.log('检测到HTTP URL');
    return trimmedUrl;
  }
  
  // 3. 微信小程序临时文件路径
  if (trimmedUrl.startsWith('wxfile://')) {
    console.log('检测到微信小程序临时文件');
    return trimmedUrl;
  }
  
  // 4. 小程序临时文件路径（其他格式）
  if (trimmedUrl.startsWith('http://tmp/') || trimmedUrl.includes('/tmp/')) {
    console.log('检测到小程序临时文件路径');
    return trimmedUrl;
  }
  
  // 5. H5环境的blob URL
  if (trimmedUrl.startsWith('blob:')) {
    console.log('检测到blob URL');
    return trimmedUrl;
  }
  
  // 6. 本地文件路径（包含temp、cache等关键词）
  if (trimmedUrl.includes('temp') || trimmedUrl.includes('cache') || 
      trimmedUrl.includes('storage') || trimmedUrl.includes('Documents')) {
    console.log('检测到本地文件路径');
    return trimmedUrl;
  }
  
  // 7. 可能是base64字符串
  if (trimmedUrl.length > 50 && !trimmedUrl.includes('/') && !trimmedUrl.includes('\\')) {
    console.log('检测到可能的base64字符串，长度:', trimmedUrl.length);
    
    // 检查base64特征
    if (trimmedUrl.startsWith('/9j/')) {
      console.log('检测到JPEG base64');
      return `data:image/jpeg;base64,${trimmedUrl}`;
    } else if (trimmedUrl.startsWith('iVBOR')) {
      console.log('检测到PNG base64');
      return `data:image/png;base64,${trimmedUrl}`;
    } else if (/^[A-Za-z0-9+/=]+$/.test(trimmedUrl)) {
      console.log('检测到通用base64格式');
      return `data:image/png;base64,${trimmedUrl}`;
    }
  }
  
  // 8. 其他情况直接返回（可能是相对路径）
  console.log('直接返回原始URL');
  return trimmedUrl;
}

// 预览图片
// 图片预览函数 - 优化版本，确保最高层级显示
function previewImage(index) {
  const currentImage = imageList.value[index];
  if (!currentImage) {
    uni.showToast({ title: '图片不存在', icon: 'none' });
    return;
  }
  
  const imageUrl = getImageUrl(currentImage);
  if (!imageUrl) {
    uni.showToast({ title: '图片URL无效，无法预览', icon: 'none' });
    return;
  }
  
  console.log(`预览第${index + 1}张图片:`, imageUrl);
  
  // 检查是否在浏览器环境中
  if (typeof window !== 'undefined' && typeof document !== 'undefined') {
    // 浏览器环境，使用自定义预览确保最高层级
    createCustomImagePreview(imageUrl, index);
  } else {
    // 小程序环境，使用原生预览
    useNativeImagePreview(imageUrl, index);
  }
}

// 创建自定义图片预览（浏览器环境）
function createCustomImagePreview(imageUrl, index) {
  // 创建遮罩层
  const mask = document.createElement('div');
  mask.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.9);
    z-index: 999999;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s ease;
  `;
  
  // 创建图片容器
  const container = document.createElement('div');
  container.style.cssText = `
    position: relative;
    max-width: 90vw;
    max-height: 90vh;
    display: flex;
    justify-content: center;
    align-items: center;
  `;
  
  // 创建图片元素
  const img = document.createElement('img');
  img.src = imageUrl;
  img.style.cssText = `
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
  `;
  
  // 创建关闭按钮
  const closeBtn = document.createElement('div');
  closeBtn.innerHTML = '×';
  closeBtn.style.cssText = `
    position: absolute;
    top: -50px;
    right: -50px;
    width: 40px;
    height: 40px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24px;
    font-weight: bold;
    color: #333;
    cursor: pointer;
    z-index: 1000000;
    transition: all 0.2s ease;
  `;
  
  // 关闭预览函数
  const closePreview = () => {
    mask.style.opacity = '0';
    setTimeout(() => {
      if (mask.parentNode) {
        document.body.removeChild(mask);
      }
    }, 300);
    document.removeEventListener('keydown', handleKeydown);
  };
  
  // 键盘事件处理
  const handleKeydown = (e) => {
    if (e.key === 'Escape') {
      closePreview();
    }
  };
  
  // 绑定事件
  closeBtn.addEventListener('click', closePreview);
  mask.addEventListener('click', (e) => {
    if (e.target === mask) {
      closePreview();
    }
  });
  document.addEventListener('keydown', handleKeydown);
  
  // 图片加载错误处理
  img.onerror = () => {
    closePreview();
    uni.showToast({ 
      title: '图片加载失败', 
      icon: 'none',
      duration: 2000
    });
  };
  
  // 组装元素
  container.appendChild(img);
  container.appendChild(closeBtn);
  mask.appendChild(container);
  document.body.appendChild(mask);
  
  // 显示动画
  setTimeout(() => {
    mask.style.opacity = '1';
  }, 10);
  
  console.log('使用自定义图片预览');
}

// 使用原生图片预览（小程序环境）
function useNativeImagePreview(imageUrl, index) {
  // 构建所有有效图片的URL列表用于预览
  const urls = imageList.value
    .map(img => getImageUrl(img))
    .filter(url => url && url.trim().length > 0);
  
  if (urls.length === 0) {
    uni.showToast({ title: '没有可预览的图片', icon: 'none' });
    return;
  }
  
  // 确保当前图片URL在预览列表中
  const currentIndex = urls.indexOf(imageUrl);
  const previewUrl = currentIndex >= 0 ? imageUrl : urls[0];
  
  console.log('预览图片配置:', { 
    current: previewUrl, 
    urls: urls, 
    totalCount: urls.length,
    currentIndex: currentIndex 
  });
  
  uni.previewImage({
    current: previewUrl,
    urls: urls,
    success: () => {
      console.log('图片预览成功');
    },
    fail: (err) => {
      console.error('图片预览失败:', err);
      console.error('预览失败的URL:', previewUrl);
      
      // 提供更详细的错误信息
      let errorMsg = '图片预览失败';
      if (err.errMsg) {
        if (err.errMsg.includes('file not found')) {
          errorMsg = '图片文件不存在';
        } else if (err.errMsg.includes('network')) {
          errorMsg = '网络错误，无法预览';
        } else if (err.errMsg.includes('format')) {
          errorMsg = '图片格式不支持';
        }
      }
      
      uni.showToast({ 
        title: errorMsg, 
        icon: 'none',
        duration: 2000
      });
    }
  });
  
  console.log('使用原生图片预览');
}

// 处理图片加载错误
function handleImageError(index) {
  const image = imageList.value[index];
  console.error(`第${index + 1}张图片加载失败`);
  console.error('失败的图片数据:', image);
  
  if (image) {
    console.error('图片URL:', getImageUrl(image));
    console.error('原始路径:', image.originalPath || '无');
    console.error('是否新上传:', image.isNewUpload || false);
  }
  
  // 如果是新上传的图片加载失败，可能是路径问题
  if (image && image.isNewUpload) {
    console.warn('新上传的图片加载失败，可能是路径处理问题');
    
    // 尝试重新处理URL
    const originalUrl = image.url;
    const processedUrl = processImageUrl(originalUrl);
    
    if (originalUrl !== processedUrl) {
      console.log('尝试使用重新处理的URL:', processedUrl);
      // 更新图片URL
      imageList.value[index] = {
        ...image,
        url: processedUrl
      };
      return; // 不显示错误对话框，让图片重新加载
    }
  }
  
  // 显示用户友好的错误处理选项
  uni.showModal({
    title: '图片显示异常',
    content: `第${index + 1}张图片无法正常显示，但不影响提交。是否删除此图片？`,
    confirmText: '删除',
    cancelText: '保留',
    success: (res) => {
      if (res.confirm) {
        console.log(`用户选择删除第${index + 1}张图片`);
        removeImage(index);
      } else {
        console.log(`用户选择保留第${index + 1}张图片`);
        // 可以在这里添加重试逻辑或其他处理
      }
    }
  });
}

function handleSubmit() {
  // 检查是否有修改
  const hasUpdatedValue = updatedValue.value && updatedValue.value.trim() !== '';
  const hasImages = imageList.value.length > 0;
  
  // 如果没有任何修改，显示确认框
  if (!hasUpdatedValue && !hasImages) {
    uni.showModal({
      title: '确认提交',
      content: '没有修改记录，确认直接提交吗？',
      confirmText: '确认提交',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户确认不修改直接提交
          submitWithoutModification();
        }
      }
    });
    return; // 直接返回，不执行后面的验证逻辑
  }
  
  // 有修改的情况下，进行正常的提交处理
  submitWithModification();
}

// 有修改时的提交处理
function submitWithModification() {
  // 验证更新值
  if (!updatedValue.value || updatedValue.value.trim() === '') {
    uni.showToast({ title: '请输入更新值', icon: 'none' });
    return;
  }
  
  // 验证佐证照片
  if (imageList.value.length === 0) {
    uni.showToast({ title: '请上传至少一张佐证照片', icon: 'none' });
    return;
  }
  
  // 获取记录ID
  const recordId = props.recordData.id || props.recordData.de_id || props.recordData.ID || props.recordData.De_id;
  
  // 验证ID是否有效
  if (!recordId) {
    uni.showToast({ title: '记录ID无效，无法提交', icon: 'none' });
    return;
  }
  
  // 在提交前，确保数据同步到全局存储
  const recordKey = `${props.recordData.misCode}_${props.recordData.siteTaskId}_${props.recordData.rowId}_${props.recordData.type}`;
  const finalData = {
    updatedValue: updatedValue.value,
    imageList: [...imageList.value],
    accProblem: accProblem.value,
    timestamp: Date.now(),
    right_value: updatedValue.value,
    acc_problem: accProblem.value,
    photo_path: [...imageList.value],
    projectId: props.recordData.misCode,
    siteId: props.recordData.siteTaskId
  };
  
  // 确保全局存储同步
  if (typeof window !== 'undefined') {
    if (!window.recordUpdateStorage) {
      window.recordUpdateStorage = {};
    }
    window.recordUpdateStorage[recordKey] = finalData;
    console.log('提交前同步数据到全局存储:', recordKey, finalData);
  }
  
  // 准备有效的图片文件数据
  console.log('当前imageList:', imageList.value);
  const validImageFiles = imageList.value
    .filter(img => {
      // 从后端恢复的图片可能没有file对象，但有url，也需要提交
      const hasValidFile = img.file !== null && img.file !== undefined;
      const hasValidUrl = img.url && typeof img.url === 'string' && img.url.trim().length > 0;
      console.log(`图片有效性检查 - file: ${hasValidFile}, url: ${hasValidUrl}`, img);
      return hasValidFile || hasValidUrl;
    }) // 过滤掉既没有file也没有有效url的图片
    .map(img => {
      if (img.file !== null && img.file !== undefined) {
        console.log('映射有效图片文件:', img.file);
        return img.file;
      } else {
        // 从后端恢复的图片，创建包含url信息的文件对象
        console.log('创建包含url信息的文件对象:', img.url);
        return {
          url: img.url,
          path: img.url, // 使用url作为路径
          name: `restored_image_${Date.now()}.jpg`,
          type: 'image/jpeg'
        };
      }
    });
  
  console.log('有效的图片文件数组:', validImageFiles);
  
  // 将表单数据提交给父组件进行暂存
  emit('submit', {
    id: recordId,
    type: props.recordData.type,
    currentValue: getCurrentValue(),
    updatedValue: updatedValue.value,
    accProblem: accProblem.value,
    imageFiles: validImageFiles,
    imageList: [...imageList.value], // 同时传递完整的图片列表
    rowData: props.recordData
  });
}

// 不修改直接提交的处理函数
function submitWithoutModification() {
  // console.log('=== 不修改直接提交 ===');
  
  // 提交数据，所有字段都用"-"代替
  emit('submit', {
    id: '-',
    type: '-',
    currentValue: '-',
    updatedValue: '-',
    imageFiles: '-',
    rowData: '-'
  });
  
  // console.log('不修改直接提交完成');
}

// 从外部加载之前的记录数据（供父组件调用）
function loadPreviousRecords(recordsData) {
  if (!recordsData || recordsData.length === 0) return;
  
  console.log('RecordUpdateModal接收到暂存记录:', recordsData);
  
}

// 暴露方法给父组件
defineExpose({
  loadPreviousRecords
});
</script>

<style scoped>
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-container {
  width: 90%;
  max-width: 650rpx;
  background-color: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.modal-close {
  height: 24px;
  width: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-text {
  font-size: 24px;
  color: #999;
  line-height: 1;
}

.modal-body {
  padding: 16px;
}

.form-item {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

/* 绿色高亮表示有修改的行 */
.form-item.modified {
  background-color: #f0f9ff;
  border: 2px solid #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 15px;
  color: #606266;
  font-weight: 500;
}

.form-item.modified .form-label {
  color: #67c23a;
  font-weight: 600;
}

.form-input {
  width: 100%;
  height: 40px;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  font-size: 14px;
  box-sizing: border-box;
}

.form-input.disabled {
  background-color: #f5f7fa;
  color: #606266;
}

.textarea-input {
  height: 80px;
  resize: none;
  line-height: 1.5;
}

.upload-area {
  display: flex;
  flex-direction: column;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.upload-button {
  width: 160rpx;
  height: 160rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2rpx dashed #dcdfe6;
  border-radius: 8rpx;
  background-color: #f5f7fa;
  transition: all 0.3s ease;
}

.upload-button:active {
  background-color: #e4e7ed;
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #c0c4cc;
  margin-bottom: 4px;
}

.upload-text {
  font-size: 12px;
  color: #909399;
}

.upload-preview {
  width: 160rpx;
  height: 160rpx;
  position: relative;
  border-radius: 8rpx;
  overflow: hidden;
  border: 2rpx solid #e4e7ed;
  background-color: #f5f7fa;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 6rpx;
  object-fit: cover;
  background-color: #fff;
  cursor: pointer;
}

.delete-image {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 36rpx;
  text-align: center;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 50%;
  font-size: 20rpx;
  z-index: 10;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.view-image {
  position: absolute;
  bottom: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  line-height: 36rpx;
  text-align: center;
  background-color: #409eff;
  color: #fff;
  border-radius: 50%;
  font-size: 16rpx;
  z-index: 10;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.delete-image:active,
.view-image:active {
  transform: scale(0.9);
}

.loading-indicator {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 5;
  border-radius: 6rpx;
}

.loading-text {
  font-size: 12px;
  color: #409eff;
  font-weight: 500;
}

.upload-badge {
  position: absolute;
  top: 4rpx;
  left: 4rpx;
  width: 32rpx;
  height: 32rpx;
  line-height: 32rpx;
  text-align: center;
  background-color: #67c23a;
  color: #fff;
  border-radius: 4rpx;
  font-size: 10px;
  font-weight: bold;
  z-index: 8;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

.form-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn {
  padding: 8px 20px;
  font-size: 14px;
  border-radius: 4px;
  margin-left: 12px;
}

.btn-cancel {
  border: 1px solid #dcdfe6;
  color: #606266;
  background-color: #fff;
}

.btn-submit {
  background-color: #409eff;
  color: #fff;
  border: none;
}

/* 图片预览遮罩层样式 - 确保最高层级显示 */
.image-preview-mask {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  background-color: rgba(0, 0, 0, 0.9) !important;
  z-index: 99999 !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview-mask.show {
  opacity: 1 !important;
}

.image-preview-container {
  max-width: 90% !important;
  max-height: 90% !important;
  position: relative !important;
}

.image-preview-img {
  max-width: 100% !important;
  max-height: 100% !important;
  object-fit: contain !important;
  border-radius: 8px !important;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5) !important;
}

.image-preview-close {
  position: absolute !important;
  top: -40px !important;
  right: -40px !important;
  width: 40px !important;
  height: 40px !important;
  background-color: rgba(255, 255, 255, 0.9) !important;
  border-radius: 50% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  font-size: 24px !important;
  font-weight: bold !important;
  color: #333 !important;
  cursor: pointer !important;
  z-index: 100000 !important;
  transition: all 0.2s ease !important;
}

.image-preview-close:hover {
  background-color: rgba(255, 255, 255, 1) !important;
  transform: scale(1.1) !important;
}

/* 确保模态框本身的层级不会影响图片预览 */
.modal-mask {
  z-index: 1000;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-preview-close {
    top: -30px !important;
    right: -30px !important;
    width: 35px !important;
    height: 35px !important;
    font-size: 20px !important;
  }
  
  .image-preview-container {
    max-width: 95% !important;
    max-height: 95% !important;
  }
}
</style>